﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.Common;
using System.Globalization;
using HRProject.Code.DTO;
using HRProject.Code.DAO;
using System.Collections.Generic;

namespace HRProject
{
    public partial class AjaxAgent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int errorAgentCode = 0;
            int errorLinkCode = 0;
            int updateAgentResult = 0;
            int updateLinkResult = 0;
            string error = "";
            string result = "";

            string sOperation = Request.Params["operation"];
            string sJobTitleLinkId = Request.Params["jobTitleLinkId"];
            string sJobTitleId = Request.Params["jobTitleId"];
		    string sAgentId = Request.Params["agentId"];
			string sFullName = Request.Params["fullName"];
			string sBirthDate = Request.Params["birthDate"];
			string sIdentifiedSerial = Request.Params["identifiedSerial"];
			string sStartDate = Request.Params["startDate"];
            string sEndDate = Request.Params["endDate"];

            bool newLink = false;
            bool newAgent = false;
            Guid agentId;
            Guid jobTitleId;
            try
            {
                jobTitleId = new Guid(sJobTitleId);
            }
            catch (Exception exp)
            {
                jobTitleId = Guid.Empty;
                Console.Out.WriteLine(exp.Message);
            }

            Guid jobTitleLinkId;
            try
            {
                jobTitleLinkId = new Guid(sJobTitleLinkId);
            }
            catch (Exception exp)
            {
                jobTitleLinkId = Guid.NewGuid();
                newLink = true;
                Console.Out.WriteLine(exp.Message);
            }

            try
            {
                agentId = new Guid(sAgentId);
            }
            catch (Exception exp)
            {
                agentId = Guid.NewGuid();
                newAgent = true;
                Console.Out.WriteLine(exp.Message);
            }

            if ("select_node".Equals(sOperation))
            {
                JobTitleLinkDAO jobTitleLinkDao = new JobTitleLinkDAO();
                BLJobTitleLink filter = new BLJobTitleLink();
                filter.Agent = new BLAgent();
                filter.Agent.Id = Guid.Empty;
                filter.Agent.FullName = string.Empty;
                filter.JobTitle = new BLJobTitle();
                filter.JobTitle.Id = jobTitleId;
                filter.StartDate = Constant.DefaultMinDate;
                filter.EndDate = Constant.DefaultMaxDate;
                List<BLJobTitleLink> jobTitleLinks = jobTitleLinkDao.Search(filter, "FullName", true, 1, 200, 1);

                result = "[";
                string format = new string('0', Convert.ToString(jobTitleLinks.Count).Length);
                for (int i = 0; i < jobTitleLinks.Count; i++)
                {
                    if (i > 0)
                    {
                        result += ",";
                    }
                    result += "{";
                    result += "\"order\":\"" + (i+1).ToString(format) + "\"";
                    result += ",\"jobTitleLinkId\":\"" + jobTitleLinks[i].Id + "\"";
                    result += ",\"jobTitleName\":\"" + jobTitleLinks[i].JobTitle.Name + "\"";
                    result += ",\"agentId\":\"" + jobTitleLinks[i].Agent.Id + "\"";
                    result += ",\"fullName\":\"" + jobTitleLinks[i].Agent.FullName + "\"";
                    result += ",\"birthDate\":\"" + jobTitleLinks[i].Agent.BirthDate.ToString(Constant.DateFormat) + "\"";
                    result += ",\"identifiedSerial\":\"" + jobTitleLinks[i].Agent.IdentifiedSerial + "\"";
                    result += ",\"startDate\":\"" + jobTitleLinks[i].StartDate.ToString(Constant.DateFormat) + "\"";
                    result += ",\"endDate\":\"" + jobTitleLinks[i].EndDate.ToString(Constant.DateFormat) + "\"";
                    result += "}";
                }
                result += "]";
                result = "{\"agents\":" + result + "}";

                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(result);
                Response.End();
                return;
            }

            if ("remove_agent".Equals(sOperation))
            {
                JobTitleLinkDAO jobTitleLinkDao = new JobTitleLinkDAO();
                BLJobTitleLink filter = new BLJobTitleLink();
                filter.Id = jobTitleLinkId;
                updateLinkResult = jobTitleLinkDao.Delete(filter, ref errorLinkCode);

                if (updateLinkResult > 0)
                {
                    AgentDAO agentDao = new AgentDAO();
                    BLAgent agent = new BLAgent();
                    agent.Id = agentId;
                    //updateAgentResult = agentDao.DeleteAgent(agent, ref errorAgentCode);
                }

                error = "[";
                if (errorAgentCode == 12)
                {
                    error += "\"" + ContentProvider.GetMessage("NotAuthorizedDetail").Replace("{0}", "xóa thông tin nhân viên") + "\"";
                }
                if (errorLinkCode == 12)
                {
                    if (errorAgentCode == 12)
                    {
                        error += ",";
                    }
                    error += "\"" + ContentProvider.GetMessage("NotAuthorizedDetail").Replace("{0}", "xóa thông tin chức vụ của nhân viên") + "\"";
                }
                error += "]";
            }
            else
            {
                DateTime birthDate;
                DateTime startDate;
                DateTime endDate;

                error = "[";
                if (sBirthDate == null || sStartDate == null || sEndDate == null
                    || !DateTime.TryParseExact(sBirthDate, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out birthDate)
                    || !DateTime.TryParseExact(sStartDate, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out startDate)
                    || !DateTime.TryParseExact(sEndDate, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out endDate))
                {
                    error += "\"" + ContentProvider.GetMessage("InvalidDateFormat") + "\"";
                }
                else
                {
                    AgentDAO agentDao = new AgentDAO();
                    BLAgent agent = new BLAgent();
                    agent.Id = agentId;
                    agent.Code = string.Empty;
                    agent.FullName = sFullName;
                    agent.Gender = 0;
                    agent.BirthDate = birthDate;
                    agent.BirthPlace = string.Empty;
                    agent.IdentifiedSerial = sIdentifiedSerial;
                    agent.MaritalStatus = string.Empty;
                    agent.People = string.Empty;
                    agent.Phone = string.Empty;
                    agent.Address = string.Empty;
                    agent.Contact = string.Empty;
                    agent.ExtraPhone = string.Empty;
                    agent.ExtraAddress = string.Empty;
                    agent.ExtraContact = string.Empty;
                    agent.Avatar = string.Empty;
                    agent.Description = string.Empty;
                    if (newAgent)
                    {
                        updateAgentResult = agentDao.QuickAddAgent(agent, ref errorAgentCode);
                    }
                    else
                    {
                        updateAgentResult = agentDao.QuickUpdateAgent(agent, ref errorAgentCode);
                    }

                    //if (!Guid.Empty.Equals(jobTitleId))
                    {
                        JobTitleLinkDAO jobTitleLinkDao = new JobTitleLinkDAO();
                        BLJobTitleLink jobTitleLink = new BLJobTitleLink();
                        jobTitleLink.Agent = agent;
                        jobTitleLink.Id = jobTitleLinkId;
                        jobTitleLink.JobTitle = new BLJobTitle();
                        jobTitleLink.JobTitle.Id = jobTitleId;
                        jobTitleLink.StartDate = startDate;
                        jobTitleLink.EndDate = endDate;
                        if (newLink)
                        {
                            updateLinkResult = jobTitleLinkDao.Add(jobTitleLink, ref errorLinkCode);
                        }
                        else
                        {
                            updateLinkResult = jobTitleLinkDao.Update(jobTitleLink, ref errorLinkCode);
                        }
                    }
                }

                if (errorAgentCode == 12)
                {
                    error += "\"" + ContentProvider.GetMessage("NotAuthorizedDetail").Replace("{0}", "cập nhật thông tin nhân viên") + "\"";
                }
                if (errorLinkCode == 12)
                {
                    if (errorAgentCode == 12)
                    {
                        error += ",";
                    }
                    error += "\"" + ContentProvider.GetMessage("NotAuthorizedDetail").Replace("{0}", "cập nhật thông tin chức vụ của nhân viên") + "\"";
                }
                error += "]";
            }

            result = "{\"statusAgent\":" + (errorAgentCode==0?"true":"false")
                + ",\"statusLink\":" + (errorLinkCode == 0 ? "true" : "false")
                + ",\"jobTitleLinkId\":\"" + jobTitleLinkId
                + "\",\"agentId\":\"" + agentId 
                + "\",\"error\": "+ error + "}";
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(result);
            Response.End();
        }
    }
}
